import 'package:file_picker/file_picker.dart';
import 'package:file_picker/src/utils.dart';
import 'package:file_picker/file_picker_platform_interface.dart';
import 'package:file_picker/src/file_picker_result.dart';
import 'dart:io';

class FilePickerOhOS extends FilePicker {
  @override
  Future<FilePickerResult?> pickFiles({
    String? dialogTitle,
    String? initialDirectory,
    FileType type = FileType.any,
    List<String>? allowedExtensions,
    Function(FilePickerStatus)? onFileLoading,
    bool allowCompression = true,
    bool allowMultiple = false,
    bool withData = false,
    bool withReadStream = false,
    bool lockParentWindow = false,
  }) async {
    final map = await FilePickerPlatform.instance.getFile();
    if (map != null && map['path'] is String) {
      final path = map['path'] as String;
      final lastPart = path.split('/').last;
      final name = lastPart.split('.').first;
      final List<PlatformFile> files = [
        PlatformFile(path: path, name: name, size: map['size'])
      ];
      return FilePickerResult(files);
    }
    return null;
  }

  @override
  Future<String?> getDirectoryPath({
    String? dialogTitle,
    bool lockParentWindow = false,
    String? initialDirectory,
  }) async {
    return null;
  }

  @override
  Future<String?> saveFile({
    String? dialogTitle,
    String? fileName,
    String? initialDirectory,
    FileType type = FileType.any,
    List<String>? allowedExtensions,
    bool lockParentWindow = false,
  }) async {
    return null;
  }

  @override
  Future<bool?> clearTemporaryFiles() async {
    final dir = await FilePickerPlatform.instance.getCacheDir();
    if (dir != null) {
      await cleanDirectory(dir);
      return true;
    }
    return false;
  }

  Future<void> cleanDirectory(String directoryPath) async {
    try {
      final directory = Directory(directoryPath);
      if (await directory.exists()) {
        for (final file in directory.listSync(recursive: true)) {
          if (file is File) {
            await file.delete();
          } else if (file is Directory) {
            await file.delete(recursive: true);
          }
        }
      }
    } catch (e) {
      print('Error cleaning directory: $e');
    }
  }
}
